import { getListDictApi, getListDictTreeApi } from '@api/api.js'

const publicCode = {
  namespaced: true,
  state: () => ({
    code: {},
  }),
  getters: {
    getCode: state => state.code,
  },
  actions: {
    // 获取公共code单级
    getListDictData({ commit, getters }, { param }) {
      const cachedData = getters.getCode[param] || []
      if (!cachedData.length) {
        return new Promise((resolve, reject) => {
          getListDictApi({
            param: param,
          })
            .then(res => {
              commit('setCode', { [param]: res.data })
              resolve(res.data)
            })
            .catch(reject)
        })
      }
    },
    // 获取公共code多级
    getListDictTreeData({ commit, getters }, { param }) {
      const cachedData = getters.getCode[param + '_TREE'] || []
      if (!cachedData.length) {
        return new Promise((resolve, reject) => {
          getListDictTreeApi({
            param: param,
          })
            .then(res => {
              commit('setCode', { [param + '_TREE']: res.data })
              resolve(res.data)
            })
            .catch(reject)
        })
      }
    },
  },
  mutations: {
    setCode(state, info) {
      state.code = { ...state.code, ...info }
    },
  },
}
export default publicCode
